package edu.pinkhub.shiro_test.config;



import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import edu.pinkhub.shiro_test.realm.ShiroDBRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


@Configuration
public class ShiroConfig {
    /**
     * 创建ShiroDBRealm交给spring容器
     *
     * @return
     */
    @Bean("shiroDBRealm")
    public ShiroDBRealm shiroDBRealm() {
        return new ShiroDBRealm();
    }

    /**
     * 安全管理器
     *
     * @param userRealm
     * @return
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("shiroDBRealm") ShiroDBRealm userRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    /**
     * 拦截器--拦截请求
     * 常用的过滤器：
     * anno:无需认证即可访问
     * authc:必须认证才能访问
     * perms:拥有对某个资源的权限才能访问
     * role:拥有某个角色权限才能访问
     * @param securityManager
     * @return
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //拦截
        HashMap<String, String> filterMap = new HashMap<>();
        //filterMap.put("/user/login", "anon");
        filterMap.put("/user/add", "perms[add]");
        filterMap.put("/user/edit", "perms[update]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        //没通过验证，触发登录拦截请求，跳转登陆页面
        shiroFilterFactoryBean.setLoginUrl("/user/toLogin");
        //触发未认证请求，跳转未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/noAuth");
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }
    //整合ShiroDialect:用于整合shiro thymeleaf
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
